<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Static Variables and Static Class Members</title>
  <meta
 content="C++ Tutorial: Static Variables and Static Class Members"
 name="description" />
  <meta
 content="C++ Tutorial, Static Variables, Static Class Members, Singleton Pattern"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Static Variables and Static Class Members</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>

</ul>
</div>
<br />
<br />
<img src="images/statics/GeyRyongSan.png" alt="GeyRyongSan"/>
<br />
<br />
<div class="bodytext" style="padding: 12px;" align="justify">

<div class="subtitle" id="staticobjects">Static Objects</div>
<p><strong>Static object</strong> is an object that persists from the time it's constructed until the end of the program. So, <strong>stack</strong> and <strong>heap</strong> objects are excluded. But global objects, objects at namespace scope, objects declared <strong>static</strong> inside classes/functions, and objects declared at file scope are included in <strong>Static objects</strong>. Static objects are destroyed when the program stops running.</p>

<br />
<br />

<div class="subtitle" id="staticstorage">Static Storage</div>
<p>Variables defined outside a function by using the keyword <strong>static</strong> have static storage duration. They persist for the entire running time of a program. </p>
<p>These variables can be classified as three groups in terms of <strong>linkage</strong>: <br />
<ul>
	<li>external linkage</li>
	<li>internal linkage</li>
	<li>no linkage</li>
</ul>
<p>Since the number of static variables stays the same throughout the life cycle of the program, they are easy to deal with for the memory system and they are allocated in a fixed block of memory. </p>
<p>Here is an example of static variables with different duration.</p>
<pre>
int a= 1;
static int b = 2;
int main() {}
void f() {
	static int c = 3;
	int d = 4;
}
</pre>
<p>All the <strong>static</strong> variables persist until program terminates. The variable <strong>d</strong> has local scope and no linkage - it's no use outside of <strong>f()</strong>. But <strong>c</strong> remains in memory even when the <strong>f()</strong> function is not being executed. By saying that <strong>c</strong> is <strong>static</strong>, we are saying that we want to allocate it once, and only once, at some point before the first time that <strong>f()</strong>, and that we do not want to deallocate it as long as our program runs.</p>
<p>Both <strong>a</strong> and <strong>b</strong> can be accessed from the point of declaration until the end of the file. But <strong>a</strong> can be used in other files because it has external linkage.</p>
<p>All static duration variables have the following initialization characteristics:</p>
<ul>
   <li>An uninitialized static variable has all its buts set to <strong>0</strong>.</li>
   <li>A static variable can be initialized only with a <strong>constant expression</strong>.</p>
</ul>
<pre>
int x;              // x set to 0
int y = 50;         // 50 is literal constant
int z = sizeof(int) // sizeof ok
int zz = 10 * x     // not allowed, x is not constant
int main() 
{...}
</pre>
<br />
<br />


<div class="subtitle" id="externconstant">Const and Extern</div>
<p>The <strong>const</strong> in C++ has gives a little bit of twist to the default storage classes. While a global variable has external linkage by default, a <strong>const</strong> global has <strong>internal</strong> linkage by default. In other words, C++ treats a global <strong>const</strong> definition as if the <strong>static</strong> had been used as in the following code.</p>
<pre>
const int a = 10;
int main() { .... 
</pre>
<p>So, the "const int a = 10" becomes "static const int a = 10". </p>
<p>However, if we want to make a constant have external linkage, we can use the <strong>extern</strong> keyword to override the default internal linkage:</p>
<pre>
extern const int a = 20;
</pre>
<p>Here, we should use the <strong>extern</strong> keyword to declare the constant in all files that use the constant. That's the difference between regular external variables and constant. For regular external variables, we don't use the keyword <strong>extern</strong> when we define a variable, but we use <strong>extern</strong> in other files using that variable. </p>
<br />
<br />


<div class="subtitle" id="staticdynamic">Static Storage and Dynamic Allocation</div>  
<p>Dynamic memory is controlled by the <strong>new</strong> and <strong>delete</strong> operators, <strong>not</strong> by <strong>scope</strong> and <strong>linkage</strong> rules. So, dynamic memory can be allocated from one function and freed from another function. </p>
<p>Although the storage schemes don't apply to dynamic memory, then <strong>do</strong> apply to <strong>automatic</strong> and <strong>static</strong> pointer variables used to keep track of dynamic memory.</p>
<p>Let's look at the following line of code:</p>
<pre>
int *ptr = new int[10];
</pre>
<p>The 40 bytes of memory allocated by <strong>new</strong> remains in memory until the <strong>delete</strong> frees it. But the pointer <strong>ptr</strong> passes from existence when the function containing this declaration terminates. </p>
<p>If we want to have the 40 bytes of allocated memory available from another function, we need to pass or return its address to that function.</p>
</p>On the other hand, if we declare <strong>ptr</strong> with external linkage, the <strong>ptr</strong> pointer will be available by using:</p>
<pre>
extern int *ptr;
</pre>
<p>However, a statement that uses <strong>new</strong> to set <strong>ptr</strong> has to be in a function because static storage variables can only be initialized with constant expressions as shown in the following example.</p>
<pre>
int *ptr;
// initialization with non-const not allowed here
// int *ptr = new int[10];	
int main() 
{
	ptr = new int[10];
...
</pre>

<br />
<br />


<div class="subtitle" id="staticclassmember">Static Class Member</div>
<p><strong>Static members</strong> exist as members of the class rather than as an instance in each object of the class. So, <strong>this</strong> keyword is not available in a <strong>static</strong> member function. Such functions may access only <strong>static</strong> data members. There is a single instance of each <strong>static</strong> data member for the entire class, which should be initialized, usually in the source file that implements the class member functions. Because the member is initialized outside the class definition, we must use fully qualified name when we initialize it:</p>
<pre>
class_name::static_member_name = value;
</pre>
<p>Here is the real life example, Car.h:</p>
<pre>
class Car
{
private:
	static int id;
public:
 	Car();
...
};
</pre>
<p>Implementation file, Car.cpp:</p>
<pre>
#include &lt;iostream&gt;

<font color="red">int Car::id = 100;</font>
...
Car::Car() {}
....
</pre>
<p>The code initializes the static <strong>id</strong> member to 100. Note again that we cannot initialize a static member variable inside the class declaration. That's because the declaration is a description of how memory is to be allocated, but it doesn't allocate memory. We allocate and initialize memory by creating an object using that format.</p>
<p>In the case of a static class member, we initialize the static member independently, with a separate statement outside the class declaration. That's because the static class member is stored separately rather than as part of an object.</p>
<p>The exception to the initialization of a static data member inside the class declaration is if the static data member is a <strong>const</strong> of integral or enumeration type.</p>
<pre>
#include &lt;iostream&gt;

class Car
{
	enum Color {silver = 0, maroon, red };  
	int year;
	int mileage = 34289;                   // error: not-static data members
	                                       // only static const integral data members 
	                                       // can be initialized within a class

	static int vin = 12345678;             // error: non-constant data member
	                                       // only static const integral data members 
	                                       // can be initialized within a class

	static const string model = "Sonata";  // error: not-integral type
	                                       // cannot have in-class initializer

	<font color="red">static const int</font> engine = 6;           // allowed: static const integral type
};

int Car::year = 2012;                          // error: non-static data members 
                                               // cannot be defined out-of-class

int main()
{
	return 0;
}
</pre>
<br />
<br />


<div class="subtitle" id="staticmemberfunction">Static Member Functions</div>
<p>Here are some characteristics of <strong>static member functions</strong>:</p>
<ul>
	<li>A static member function can only access <strong>static member data</strong>, <strong>static member functions</strong> and <strong>data and functions outside the class</strong>. So, we must take note not to use static member function in the same manner as non-static member function, as non-static member function can access all of the above including the static data member. </li>
	<li>We must first understand the concept of static data while learning the context of static functions. It is possible to declare a data member of a class as static irrespective of it being a public or a private type in class definition. If a data is declared as static, then the static data is created and initialized only once. Non-static data members are created again and again. For each separate object of the class, the static data is created and initialized only once. As in the concept of static data, all objects of the class in static functions share the variables. This applies to all objects of the class.</li>
	<li>A non-static member function can be called only after instantiating the class as an object. This is not the case with static member functions. A static member function can be called, even when a class is not instantiated.</li>
	<li>A static member function cannot have access to the <strong>this</strong> pointer of the class. </li>
	<li>A non-static member function can be declared as virtual but care must be taken not to declare a static member function as virtual. </li>

</ul>
<br />
<br />
<br />


<div class="subtitle" id="staticSingleton">Static - Singleton Pattern</div>
<p>Singleton design pattern is a good example of static member function and static member variable. 
In this pattern, we put constructor in <strong>private</strong> section not in public section of a class. So, 
we can not access the constructor to make an instance of the class. Instead, we put a public function which is 
<strong>static</strong> function. The <strong>getInstance()</strong> will make an instance only once. Note that if this method is not static, there is no way to invoke the <strong>getInstance()</strong> even though it is public method. That's because we do not have any instance of <strong>Singleton</strong>.</p>
<pre>
#include &lt;iostream&gt;

using namespace std;

class Singleton
{
public:
	<font color="red">static</font> Singleton *getInstance();
<font color="red">private:</font>
	<font color="red">Singleton() {}</font>
	<font color="red">static</font> Singleton *instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() {
		if(!instance) {
			instance = new Singleton();
			cout << "getInstance(): First instance\n";
			return instance;
		}
		else {
			cout << "getInstance(): previous instance\n";
			return instance;
		}
}

int main()
{
	Singleton* s1 = Singleton::getInstance();
	Singleton* s2 = Singleton::getInstance();

	return 0;
}
</pre>
<p>Output is:</p>
<pre>
getInstance(): First instance
getInstance(): previous instance
</pre>
<br />
<br />
<br />
<img src="images/statics/KwanAkSan.png" alt="KwanAkSan"/>
<br />
 
<br />
<br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>

</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
